package servlet.admin;

import entity.Manager;
import entity.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.admin.ManagerAddService;
import service.admin.impl.ManagerAddServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * ManagerAddServlet
 *
 * @author ChenYanMei
 * @version 2023/9/5
 */
@WebServlet("/admin/managerAdd")
public class ManagerAddServlet extends HttpServlet {
    ManagerAddService service = new ManagerAddServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 接收参数
        String name = req.getParameter("name");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        int result = 0;
        int count = 0;

        // 返回参数
        int code = 1;
        String msg = "";
        PrintWriter out = resp.getWriter();
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject  = new JSONObject();
        Manager manager = new Manager(name, account, password, email);
        // 进行查询
        if(manager.getName()==null || manager.getName().equals("") || manager.getAccount()==null ||
                manager.getAccount().equals("") || manager.getPassword()==null || manager.getPassword().equals("") ||
                manager.getEmail()==null || manager.getEmail().equals("")) {

            msg = "参数不能为空";
            out.print(Util.jsonResponse(code, msg, null));
        }else {
            result = service.add(manager, account);

            // 返回数据
            if (result == 1 && count == 0) {
                code = 0;
                msg = "添加成功";
            } else if (count > 0) {
                msg = "账号重复";
            } else {
                msg = "添加失败";
            }
        }
            out.print(Util.jsonResponse(code, msg, null));
    }
}
